/**
 * @Units.java  COPYRIGHT xiaojian
 * 
 * Created on 2017年10月27日 下午4:35:30
 */
package xj.toolkit.ebus.unit.yaml;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;

import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;

/**
 * @author <a href="mailto:cxj2000@gmail.com">xiaojian.cao</a>
 *
 */
public class Units {

	/**
	 * Map: name <-> yamlUnitSource.
	 */
	private Map<String, YamlUnitSource> unitMap = null;

	public void setUnits(List<YamlUnitSource> units) {
		Preconditions.checkArgument(units != null && units.size() > 0);

		Multimap<String, YamlUnitSource> multiMap = ArrayListMultimap.create();
		for (YamlUnitSource us : units) {
			multiMap.put(us.getName(), us);
		}

		for (String key : multiMap.keySet()) {
			Collection<YamlUnitSource> lst = multiMap.get(key);
			if (lst.size() == 0 || lst.size() > 1) {
				throw new IllegalArgumentException("Unit[" + key + "] has repeated.");
			}
		}
		this.unitMap = Maps.uniqueIndex(units, new Function<YamlUnitSource, String>() {

			@Override
			public String apply(YamlUnitSource input) {
				return input.getName();
			}
		});

	}

	/**
	 * 通过名字得到YamlUnitSource。
	 * 
	 * @param name
	 * @return
	 */
	public YamlUnitSource getUnitSourceByName(String name) {
		Preconditions.checkArgument(StringUtils.isNoneBlank(name));

		return unitMap.get(name);
	}

	@SuppressWarnings("unchecked")
	public List<YamlUnitSource> getUnits() {
		return (List<YamlUnitSource>) (unitMap != null && unitMap.size() > 0 ? Lists.newArrayList(unitMap.values())
				: Lists.newArrayList());
	}

	public String toString() {
		return ToStringBuilder.reflectionToString(unitMap);
	}
}
